package com.tyut.musicdreamer.service.user.utils;

import com.tyut.musicdreamer.service.user.enums.UserErrorCode;
import com.tyut.musicdreamer.service.user.exception.UserBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class FileUtils {

    @Value("${upload.avatar.max-size}")
    private DataSize maxFileSize;

    @Value("${upload.avatar.allowed-extensions:jpg,jpeg,png,gif}")
    private List<String> allowedTypes;

    @Value("${upload.avatar.base-path}")
    private String basePath;

    public String uploadAvatar(MultipartFile file) {
        // 检查文件大小
        if (file.getSize() > maxFileSize.toBytes()) {
            throw new UserBusinessException(UserErrorCode.FILE_SIZE_EXCEEDED);
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new UserBusinessException(UserErrorCode.UNSUPPORTED_FILE_TYPE);
        }
        
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!allowedTypes.contains(extension)) {
            throw new UserBusinessException(UserErrorCode.UNSUPPORTED_FILE_TYPE);
        }

        try {
            // 生成文件名
            String filename = UUID.randomUUID() + "." + extension;

            // 确保目录存在
            File uploadDir = new File(basePath);
            if (!uploadDir.exists() && !uploadDir.mkdirs()) {
                throw new UserBusinessException(UserErrorCode.FILE_UPLOAD_FAILED);
            }

            // 保存文件
            File destFile = new File(uploadDir, filename);
            file.transferTo(destFile);

            // 返回文件URL
            return "/uploads/" + filename;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new UserBusinessException(UserErrorCode.FILE_UPLOAD_FAILED);
        }
    }
} 